package org.redrock.test.repository;

import org.redrock.test.bean.RequestInfo;
import org.redrock.test.bean.UserInfo;
import org.redrock.test.exception.WeixinException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;

@Repository
public class UserInfoRepository {

    private Logger logger = LoggerFactory.getLogger(UserInfoRepository.class);

    private String getUserInfoApiFormat = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN";
    @Autowired
    private NetworkRepository networkRepository;
    @Autowired
    private GsonRepository gsonRepository;
    @Autowired
    private AccessTokenRepository accessTokenRepository;

    /**
     * 通过 openId 获取用户信息
     * @param openId
     * @return
     */
    public UserInfo getUserInfo(String openId) throws WeixinException {
        String accessToken = accessTokenRepository.getAccessToken();
        String getUserInfoApi = String.format(
                getUserInfoApiFormat,
                accessToken,
                openId
        );
        RequestInfo requestInfo = new RequestInfo("get", getUserInfoApi);
        String data = networkRepository.curl(requestInfo);
        System.out.println(data);
        Map<String, Object> mapData = gsonRepository.fromJson(data, HashMap.class);
        if (mapData.get("errcode") != null || mapData.get("errmsg") != null) {
            String msg = mapData.get("errcode") + " : " + mapData.get("errmsg");
            throw new WeixinException(HttpStatus.BAD_REQUEST, msg);
        }
        UserInfo userInfo = gsonRepository.fromJson(data, UserInfo.class);
        return userInfo;
    }
}